package servlets;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import app.RemoteStructure;


public class RemoteFileBrowser extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    public RemoteFileBrowser() {
        super();
        structure = RemoteStructure.getInstance();
    }

    protected String filter;
    
    protected RemoteStructure structure;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String path = request.getParameter("path");
		filter = request.getParameter("filter");
		Boolean force = Boolean.valueOf(request.getParameter("force"));
		
		if(structure.lastUpdate == 0 || force){
			File dir = new File(path);
			
			if(!dir.exists() || !dir.isDirectory()){
				response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
				return;
			}
			
			long time = System.currentTimeMillis();
			
			Document doc = DocumentHelper.createDocument();
			Element root = DocumentHelper.createElement("node");
			root.addAttribute("timestamp", ""+time);
			
			doc.setRootElement(root);

			id = 0;
			fileList = new ArrayList<File>();
			
			Element node = getChild(dir);

			if (node != null) {
				root.add(node);
			}
			
			structure.fileList = fileList;
			structure.responseXML = doc.asXML();
			
			if(!structure.remoteDirectory.equalsIgnoreCase(path)){
				structure.remoteDirectory = path;
			}

		}
		
		response.setCharacterEncoding("utf-8");
	    response.setContentType("application/xml;");
		response.getWriter().write(structure.responseXML);
	}
	
	private int id;
	private ArrayList<File> fileList;
	

	private Element getChild(File file) {
		if (file.exists() && file.canRead() ){
			Element root = DocumentHelper.createElement("node");
			root.addAttribute("name", file.getName());
			if(file.isDirectory()){
				root.addAttribute("dir", "1");
				File[] files = file.listFiles();
				for (File f : files) {
					Element node = getChild(f);
					if (node != null) {
						root.add(node);
					}
				}
			}else{
				String filename = file.getName();
				if(filter != null && filter.length() > 0 ){
					String extension = filename.substring(filename.length()-filter.length()-1);
					if(!extension.equalsIgnoreCase("."+filter)){
						return null;
					}
				}
				
				root.addAttribute("id", "" + id);
				fileList.add(id, file);
				id++;
				
				root.addAttribute("dir", "0");
				root.addAttribute("path", file.getAbsolutePath());
			}
			return root;
		}

		return null;
	}
}
